<?php
    /**
     * Created by PhpStorm.
     * User: jackhhy
     * Date: 2019/6/26-14:38
     * Link: https://gitee.com/luckygyl/luckyAdmin
     * FileName: Login.php
     * Keys: ctrl+alt+L/ctrl+s(代码格式化) ctrl+J(代码提示) ctrl+R(替换)ALT+INSERT(生成代码(如GET,SET方法,构造函数等) , 光标在类中才生效)
     * CTRL+ALT+O (优化导入的类和包 需要配置) SHIFT+F2(高亮错误或警告快速定位错误)
     * CTRL+SHIFT+Z(代码向前) CTRL+SHIFT+/ (块状注释) ctrl+shift+enter(智能完善代码 如if())
     *
     **************************************************************
     *                                                            *
     *   .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.       *
     *    |                     ______                     |      *
     *    |                  .-"      "-.                  |      *
     *    |                 /            \                 |      *
     *    |     _          |              |          _     |      *
     *    |    ( \         |,  .-.  .-.  ,|         / )    |      *
     *    |     > "=._     | )(__/  \__)( |     _.=" <     |      *
     *    |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *
     *    |           "=._"(_     ^^     _)"_.="           |      *
     *    |               "=\__|IIIIII|__/="               |      *
     *    |              _.="| \IIIIII/ |"=._              |      *
     *    |    _     _.="_.="\          /"=._"=._     _    |      *
     *    |   ( \_.="_.="     `--------`     "=._"=._/ )   |      *
     *    |    > _.="                            "=._ <    |      *
     *    |   (_/                                    \_)   |      *
     *    |                                                |      *
     *    '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
     *                                                            *
     *                    JUST FIND YOUR BUG !                    *
     **************************************************************
     */

    namespace app\admin\controller;

    use service\StringService;
    use service\UtilService;
    use think\Controller;
    use think\Exception;
    use think\Request;
    use think\Session;

    class Login extends Controller
    {

        protected function _initialize()
        {
            parent::_initialize(); // TODO: Change the autogenerated stub
        }


        /**
         * @param Request $request
         * @return mixed
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @throws \think\exception\PDOException
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: index
         * @describe:登录页面及登录请求
         */
        public function index(Request $request)
        {

            if($request->isPost()) {

                $this->BidLoginIP(); //判断禁止登陆的IP

                $data             = $request->only(['username', 'password', '__token__','code']);
                $data['username'] = StringService::remove_xss($data['username']); //去除xss攻击
                try {
                    $info = db("admin_member")->where(["username" => "".$data['username'].""])->find();
                } catch (Exception $exception) {
                    $this->error($exception->getMessage());
                }

                if(empty($info)) {
                    $this->error("用户名错误");
                }
                if($info['password']!=UtilService::think_encrypt($data['password'])) {
                    $this->error("密码输入错误");
                }

                if(!captcha_check($data['code'])){
                    $this->error("验证码错误");

                }

                if((int)$info['status']!=1) {
                    $this->error("该账号已被禁用，无法登陆后台！");
                }

                $role = db("admin_role")->where("id", $info['role_id'])->value("name");//查询角色

                $info['role_name'] = $role;
                $da                = ['logins' => $info["logins"] + 1, 'login_ip' => UtilService::getip(), 'last_login_time' => time(), 'id' => $info['id']];


                AddLogs(['admin_name'=>$info['username'],'browse'=>UtilService::getBrowser(),'login_time'=>date("Y-m-d H:i:s",time()),'type'=>1]);//添加日志

                db("admin_member")->update($da);

                session('admin_info', $info); //保存数据到session

                $this->success("登陆成功");

            }

            //登录检测
            if(Session::has('admin_info.username')) {
                $this->redirect('Index/index');
            }

            return $this->fetch();
        }


        /**
         * @return bool
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: BidLoginIP
         * @describe:判断禁止Ip
         */
        public function BidLoginIP(){
            $set=new \app\admin\model\Setting();
            $ipdata=$set->getSetting();
            $ips=$ipdata['safe']['forbid_ip'];
            if(empty($ips)){
                return true;
            }
            $ip=UtilService::getip(); //获取当前IP
            $ok=@explode(",",$ips);
            if(in_array($ip,$ok)){
                $this->error("禁止登陆的IP");
            }
        }

        /**
         * @author: Jackhhy
         * @name: LoginOut
         * @describe:退出登录
         */
        public function LoginOut()
        {
            session('admin_info', null);
            $this->success("退出成功");
        }

    }